Prototype
It is used to create objects by copying an existing object (called the prototype) rather than creating new instances from scratch. This pattern is particularly useful when object creation is costly (due to complexity, time, or memory), and when the object to be created is similar to an existing one.
Structure
- Prototype: An interface (or abstract class) that defines the
clone()method. - Concrete Prototype: Implements the
clone()method to create a copy of the object. - Client: Creates a new object by calling
clone()on the prototype.
Example
// Step 1: Define Prototype Interface
interface Prototype {
Prototype clone(); // Method for cloning
}
// Step 2: Create Concrete Prototype
class SoftwareLicense implements Prototype {
private String licenseType;
private String ownerName;
public SoftwareLicense(String licenseType, String ownerName) {
this.licenseType = licenseType;
this.ownerName = ownerName;
}
@Override
public SoftwareLicense clone() {
return new SoftwareLicense(this.licenseType, this.ownerName);
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public void displayLicense() {
System.out.println("License Type: " + this.licenseType + ", Owner: " + this.ownerName);
}
}
// Step 3: Client code
public class Main {
public static void main(String[] args) {
SoftwareLicense originalLicense = new SoftwareLicense("Premium", "Alice");
originalLicense.displayLicense();
SoftwareLicense clonedLicense1 = originalLicense.clone();
System.out.println("\nFirst Copy");
clonedLicense1.displayLicense();
clonedLicense1.setOwnerName("Bob");
clonedLicense1.displayLicense();
SoftwareLicense clonedLicense2 = originalLicense.clone();
System.out.println("\nSecond Copy");
clonedLicense2.displayLicense();
clonedLicense2.setOwnerName("Charlie");
clonedLicense2.displayLicense();
SoftwareLicense nestedClone1 = clonedLicense1.clone();
System.out.println("\nFirst Nested Copy");
nestedClone1.displayLicense();
nestedClone1.setOwnerName("John");
nestedClone1.displayLicense();
}
}